<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member\cloud;

use app\common\model\member\Wallet;
use app\manage\model\Member;
use buwang\base\MemberBaseController;
use buwang\traits\CrudControllerTrait;
use think\db\exception\PDOException;
use think\facade\View;

class Packet extends MemberBaseController
{
    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();

        $this->model = new \app\common\model\cloud\Packet();
    }

    /**
     * 查看
     * @menu true
     */
    public function index()
    {
        if (request()->isAjax()) {
            $page = request()->get('page/d', 1);
            $limit = request()->get('limit/d', 10);

            //TODO 获取搜索条件
            //TODO 如果有不属于表内的字段,查询会报错
            $where = request()->get();
            unset($where['page']);
            unset($where['limit']);
            foreach ($where as $k => $v) {
                if (!$v && $v !== '0' && $v !== 0 && $v !== false) {
                    unset($where[$k]);
                }
            }

            try {
                $total = $this->model->where($where)->count();
//                $list = $this->model->where($where)->order($this->model->getPk(), 'DESC')->page($page, $limit)->select();
                $list = $this->model->where($where)->order($this->model->getPk(), 'DESC')->select();
            } catch (\Exception $e) {
                return $this->error('查询失败', ['errorMsg' => $e->getMessage()]);
            }

            $data = compact("total", 'list');
            return $this->success('successful', $data);
        }

        //搜索条件
        $where = [];
        $service_id = request()->param('service_id/d', 0);
        if ($service_id !== 0) $where['service_id'] = $service_id;
        View::assign(compact('where'));

        return view();
    }

    /**
     * 购买
     * @menu true
     */
    public function buy()
    {
        if (request()->isPost()) {
            $id = request()->post('id/d', 0);
            $paypwd = request()->post('paypwd/s', '');

            if (!preg_match("/^[0-9]{6}$/", $paypwd)) return self::setError('请输入6位数字支付密码');

            $packet = $this->model->find($id);
            if (!$packet) return $this->error('套餐不存在');

            //TODO 验证支付密码
            if (!Member::checkPassword($paypwd, $this->user['safe_password'])) return $this->error('支付密码错误');

            $this->model->startTrans();
            try {
                //TODO 扣余额
                $res1 = Wallet::changeMoney($this->uid, 'cloud_packet', 0 - $packet['price'], '购买云市场套餐');
                if (!$res1) {
                    $this->model->rollback();
                    return $this->error(Wallet::getError());
                }
                //TODO 加次数
                $res2 = \app\common\model\cloud\Wallet::changeAmount($this->uid, $packet['service_id'], 'buy', $packet['amount'], '购买套餐');
                if (!$res2) {
                    $this->model->rollback();
                    return $this->error(\app\common\model\cloud\Wallet::getError());
                }
                //TODO 生成购买记录
                $orderParam = [
                    'member_id' => $this->uid,
                    'service_id' => $packet['service_id'],
                    'packet_id' => $packet['id'],
                    'amount' => $packet['amount'],
                    'price' => $packet['price'],
                    'days' => $packet['days'],
                ];
                $res3 = \app\common\model\cloud\Order::create($orderParam);

                $this->model->commit();
            } catch (PDOException $e) {
                $this->model->rollback();
                return $this->error('新增失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success();
        }
    }
}
